package com.sky.task;

import com.sky.entity.Orders;
import com.sky.mapper.OrderMapper;
import com.sky.service.OrderService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.time.ZoneOffset;
import java.util.List;

/**
 * @Description TODO
 * @Author dingchunlin
 * @Date 2023/8/21 19:20
 * @Version 1.0.0
 */
@Component
@Slf4j
public class MyTsak {

    @Autowired
    private OrderMapper orderMapper;

    /**
     * 每分钟一次检查是否存在未支付的订单
     */
    @Scheduled(cron = "0 1-59 * * * ? ")
    public void processTimeoutOrder(){
        log.info("定时任务执行，查询是否存在超时订单{}",LocalDateTime.now());
        //首先我们获取现在所有未支付的订单
        List<Orders> list = orderMapper.getOrderListByStatus(Orders.PENDING_PAYMENT);
        if (list != null && list.size() > 0) {
            for (Orders orders : list) {
                //获取下单的时间
                LocalDateTime orderTime = orders.getOrderTime();
                //获取下单时间的毫秒值
                long start = orderTime.toInstant(ZoneOffset.of("+8")).toEpochMilli();
                //获取当前时间毫秒值
                long current = System.currentTimeMillis();
                //判断是否已经超过15分值
                if((current - start)/ 1000 / 60 > 15) {
                    log.info("订单号为：{}的订单因超时已取消",orders.getNumber());
                    orders.setCancelReason("订单超时，自动取消");
                    orders.setStatus(Orders.CANCELLED);
                    orders.setCancelTime(LocalDateTime.now());
                    orderMapper.updateOrders(orders);
                }
            }
        }
    }

    /**
     * 处理一直在派送中的订单
     */
    @Scheduled(cron = "0 0 1 * * ?")
    public void processDeliveryOrder(){
        log.info("定时任务执行，查询是否存在派送中但已完成的订单{}",LocalDateTime.now());
        //首先我们获取现在所有未支付的订单
        List<Orders> list = orderMapper.getOrderListByStatus(Orders.DELIVERY_IN_PROGRESS);
        if (list != null && list.size() > 0) {
            for (Orders orders : list) {
                orders.setStatus(Orders.COMPLETED);
                orders.setDeliveryTime(LocalDateTime.now());
                orderMapper.updateOrders(orders);
                log.info("订单号为：{}的订单状态变更为已完成",orders.getNumber());
            }
        }
    }
}
